<template>
  <div class="user-manage">
    <div class="query-form">
      <el-form :inline="true" :model="user" ref="form">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="user.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="user.userName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="用户状态" prop="state">
          <el-select v-model="user.state">
            <el-option :value="0" label="所有"></el-option>
            <el-option :value="1" label="在职"></el-option>
            <el-option :value="2" label="离职"></el-option>
            <el-option :value="3" label="试用期"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary">新增</el-button>
        <el-button type="danger" @click="handlePatchDel">批量删除</el-button>
      </div>
      <el-table :data="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-for="item in columns"
          :key="item.group"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :formatter="item.formatter"
        >
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button @click="handleClick(scope.row)" size="mini"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" @click="handleDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination 
      background 
      layout="prev, pager, next" 
      :total="pager.total"
      class="pagination"
      :page-size="pager.pageSize"
      @current-change="handleCurrentChange"></el-pagination>
    </div>
    <!-- 弹框 -->
    <el-dialog>
        <el-form :model="userForm">
            <el-form-item label="用户名" prop="userName">
                <el-input v-model="userForm.userName" placeholder="请输入用户名"/>
            </el-form-item>
            <el-form-item label="用户邮箱" prop="userEmail">
                <el-input v-model="userForm.userEmail" placeholder="请输入用户邮箱" />
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="userForm.mobile" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="岗位" prop="job">
                <el-input v-model="userForm.job" placeholder="请输入岗位名" />
            </el-form-item>
            <el-form-item label="系统角色" prop="roleList">
                <el-select v-model="userForm.roleList">
                    <el-option></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="" prop="">
                <el-cascader 
                    :options="[]" 
                    :props="{ checkStrictly: true, value:'_id',label: 'deptName'}"
                    clearable>
                </el-cascader>
            </el-form-item>
        </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getCurrentInstance, reactive, ref, onMounted, toRefs } from "vue";
export default {
  name: "user",
  setup() {
    // ctx是vue3中的上下文全局对象
    const { ctx } = getCurrentInstance();
    // 初始化用户表单对象
    const user = reactive({
        state: 0
    });
    // 初始化用户列表数据
    const userList = ref([]);
    // 初始化分页对象
    const pager = reactive({
      pageNum: 1,
      pageSize: 10,
    });
    // 定义动态表格-格式
    const columns = reactive([
      { label: "用户ID", prop: "userId" },
      { label: "用户名", prop: "userName" },
      { label: "用户邮箱", prop: "userEmail" },
      // 用户角色和状态的格式化：赋予role和state字段的动态显示，而非千篇一律的管理员/在职
      { label: "用户角色", prop: "role", 
      formatter(row,column,value){
          console.log(row,column,value); 
          return {0: '管理员', 1: '普通用户'}[value];
        } 
      },
      { label: "用户状态", prop: "state", 
      formatter(row,column,value){
          return {0:'在职', 1: '离职', 2:'试用期'}[value]
        } 
      },
      { label: "注册时间", prop: "createTime" },
      { label: "最后登录时间", prop: "lastLoginTime" },
    ]);

    // 选中用户列表的对象的id集合arr
    const checkedUserIds = ref([])
    // 初始化接口调用
    onMounted(() => { 
      getUserList(); // 进入页面后就要查询一下用户列表渲染出来
     
    });
    // 获取用户列表
    const getUserList = async () => {
      let params = {...user, ...pager}; // 初始化页面查询用户列表需要user的state和分页展示条数这两个参数对页面渲染
      try {
        // 通过ctx是可以取到$request/$api这两个挂在载app.config.globalProperties上的方法的
        const { list, page } = await ctx.$api.getUserList(params);
        userList.value = list;
        pager.total = page.total;
      } catch (err) {}
    };

    // 查询事件，获取用户列表
    const handleQuery = () => {
        getUserList();
    }
    // 重置查询表单
    const handleReset = () => {
        // 获取表单句柄form,使用elementui的官方api:resetFields()进行重置表单数据,
        // el-form-item的prop必填，不然获取不到对应数据导致无法重置
        ctx.$refs.form.resetFields(); 
    }

    // 分页事件处理,current =>当前页数
    const handleCurrentChange = (current) => {
        pager.pageNum = current
        getUserList()
    }

    // 用户单个删除，逻辑：删除用户的id对应的用户数据,删除成功后需要重新获取列表更新页面
    const handleDel = async (row) => {
        await ctx.$api.userDel({
            userId: [row.userId]
        })
        ctx.$message.success('删除成功')
        getUserList()
    }

    // 批量删除 逻辑：需要获取当前选中要删除的id集合,再批量删除，删除成功后需要重新获取列表更新页面
    const handlePatchDel = async() => {
        if(checkedUserIds.value.length === 0){
            ctx.$message.error('请选择要删除的用户!')
            return
        }
        const res = await ctx.$api.userDel({
            userIds:checkedUserIds.value
        })
        if(res.nModified > 0){
            ctx.$message.success('删除成功')
            getUserList();
        } else {
            ctx.$message.success('删除失败')
        }
        
    }

    // table表格多选触发函数
    const handleSelectionChange = list => {
        // console.log(val.userId)
        let arr = [];
        list.map(item => arr.push(item.userId))
        checkedUserIds.value = arr
        // console.log(checkedUserIds.value)
    }

    return {
      user,
      userList,
      columns,
      pager,
      getUserList,
      checkedUserIds,
      handleQuery,
      handleReset,
      handleCurrentChange,
      handleDel,
      handlePatchDel,
      handleSelectionChange
    };
  },
};
</script>

<style lang="scss" scoped>
</style>
